import config from '@/config';
import { getProxyUrls, setProxyDirect, setProxyFixedServers, setProxyPAC } from '@/lib/proxy';
import { useProxyStore } from '@/store/proxy';

export function useProxy(isReady: boolean) {
  const dispatch = useProxyStore((state) => state.dispatch);
  const proxyList = useProxyStore((state) => state.proxyList);
  const useProxyTimeout = useProxyStore((state) => state.useProxyTimeout);

  // 初始化时使用直连
  useEffect(() => {
    async function initProxy() {
      await setProxyDirect();
      dispatch({
        type: 'update',
        update(draftState) {
          draftState.currentProxy = config.proxyDirectLabel;
        },
      });
    }
    initProxy();
  }, []);

  // 初始时自动切换到代理
  useEffect(() => {
    const timmer = setTimeout(() => {
      if (isReady) {
        setFirstProxy();
      }
    }, useProxyTimeout);
    return () => {
      clearTimeout(timmer);
    };
  }, [useProxyTimeout, isReady]);

  // 设置代理列表中的第一个为代理
  const setFirstProxy = useCallback(async () => {
    const proxyUrls = getProxyUrls(proxyList);
    const proxyUrl = proxyUrls[0] || config.proxyDirectLabel;
    if (proxyUrl === config.proxyDirectLabel) {
      await setProxyDirect();
    } else {
      const UrlObj = new URL(proxyUrl);
      // await setProxyFixedServers({
      //   scheme: UrlObj.protocol.replace(':', ''),
      //   host: UrlObj.hostname,
      //   port: +UrlObj.port,
      // });
      await setProxyPAC(
        {
          host: UrlObj.hostname,
          port: +UrlObj.port,
        },
        ['www.gigab2b.com'],
      );
    }
    dispatch({
      type: 'update',
      update(state) {
        state.currentProxy = proxyUrl;
      },
    });
  }, [proxyList]);

  return {
    setFirstProxy,
  };
}
